package com.berchen.id;

/**
 * 雪花算法 源码
 */
public class SnowFlake {
    // 下面两个每个5位，加起来就是10位的工作机器ID
    private long workerId;  // 工作ID
    private long datacenterId;  // 数据ID

    // 12 位的序列号
    private long sequence;

    /**
     * @param workerId     工作ID 5位
     * @param datacenterId 数据ID 5位
     * @param sequence
     */
    public SnowFlake(long workerId, long datacenterId, long sequence) {

        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker ID can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter ID can't be greater than %d or less than 0", maxDatacenterId));
        }
        System.out.printf("worker starting. timestamp left shift %d,datacenter id bits %d,worker id bits %d,sequence bits %d,workerId %d",
                timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId);
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        this.sequence = sequence;
    }

    // 初始化时间戳
    private long twepoch = 1288834974657L;
    // 长度为5
    private long workerIdBits = 5L;
    private long datacenterIdBits = 5L;
    // 最大值
    private long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    // 序列号ID长度
    private long sequenceBits = 12L;
    // 序列号最大值
    private long sequenceMask = -1L ^ (-1L << sequenceBits);    // 4095

    // 工作ID需要左移的位数 12位
    private long workerIdShift = sequenceBits;
    // 数据ID 需要左移的位数 12+5 =17 位
    private long datacenterIdShift = sequenceBits + workerIdBits;
    // 时间戳 需要左移的位数  12+5+5 =22位
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    // 上次时间戳，初始值为负数
    private long lastTimestamp = -1L;


    /**
     * 下一个ID生成算法
     *
     * @return
     */
    public synchronized long nextId() {
        long timestamp = timeGen();
        // 获取当前时间戳如果小于上次时间戳，则表示时间戳获取出现异常
        if (timestamp < lastTimestamp) {
            System.out.printf("clock is moving backwards, Rejecting requests until %d.", lastTimestamp);
            throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        // 获取当前时间戳如果等于上次时间戳
        // 说明：还除在同一毫秒内，则在序列号+1，否则序列号赋值为0 ，从0 开始
        if (lastTimestamp == timestamp) {   // 0-4095
            sequence = (sequence + 1) & sequenceMask;   // 4096 & 4095 =0
            if (sequence == 0) {
                // 拿下一个时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }
        // 将上次时间戳刷新
        lastTimestamp = timestamp;
        /**
         * 返回结果：
         *(timestamp-twepoch)<<timestampLeftShift 表示将时间戳减去初始时间戳，再左移相应位数
         * datacenterId<<datacenterIdShift 表示将数据ID左移相应位数
         * workerId<<workerIdShift 表示将工作ID左移相应位数
         * | 是按为或运算符，只有当x y 都为0 时才为0  其他结果都为1
         * 因为个部分只有相应位上的值有意义，其他位上都是0 ，所以各部分的值进行| 运算能得到最终拼接好的ID
         */
        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
    }

    /**
     * 获取时间戳 并与上次时间戳进行比较
     *
     * @param lastTimestamp
     * @return
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 获取系统时间戳
     *
     * @return
     */
    private long timeGen() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {


        System.out.println(4096&4095);

        // 2的5 次方
        SnowFlake snowFlake = new SnowFlake(21, 10, 0);
        for (int i = 0; i < 100; i++) {
            System.out.println(snowFlake.nextId());
        }
    }
}
